import type { StudentProfile } from '@/api/types/student'
import { handleApiError } from '@/api'
import { studentApi } from '@/api/modules/student'
import { EntranceTestStatus } from '@/enums/course'
import { defineStore } from 'pinia'

interface State {
  studentId: number
  lessonId: number
  studentInfo: StudentProfile
}

export const useCurrentStudentInfoStore = defineStore(
  'currentStudentInfo',
  {
    state: (): State => {
      return {
        studentId: 0,
        lessonId: 0,

        studentInfo: {
          studentId: 0,
          name: '',
          is_entrance_test: EntranceTestStatus.NOT_EXIST,
        },
      }
    },
    getters: {
      studentName: state => state.studentInfo.name,
      // 是否存在入学测评
      isEntranceTest: state => state.studentInfo.is_entrance_test === EntranceTestStatus.EXIST,
    },
    actions: {
      setStudentId(studentId: number) {
        this.studentId = studentId
      },
      setLessonId(lessonId: number) {
        this.lessonId = lessonId
      },
      async fetchStudentInfo() {
        const [error, result] = await studentApi.getStudentProfile({
          studentId: this.studentId,
          lessonId: this.lessonId,
        })
        if (error) {
          handleApiError(error)
          return
        }
        this.studentInfo = result.data
        return result.data
      },
    },
    persist: true,
  },
)
